<!--
@Descripttion 导出
@version 1.0.0
@Author Bell
@ 使用
  引入组件
    import ExportData from '@/components/table/export-data'
  注册组件
    components: {
      ExportData
    }
  使用
    <ExportData :params="exportParams" :url="'/xxx/xxx'" :list="pageList" :select="[]" />
    <ExportData :params="exportParams" :url="'/xxx/xxx'" :list="pageList" :select="[]" keyStr="id:ids" />
    params Object 必填             导出全部-参数
    url    String 必填             导出全部-接口地址
    list   Array  必填             导出全部-表格当前列表(用于判断是否有数据有才能导出)
    select Array  必填             导出选中-选中的列表
    keyStr String 默认值('id:ids') 导出选中-key标示 如传入waybillNo:waybillNos 则key取值为waybillNo导出时参数字段名为waybillNos
 -->
<template>
  <el-select v-model="value" @change="exportData" class="export-btn" size="small">
    <el-option :label="this.$t('button.Export all')" key="all" value="all"></el-option>
    <el-option :label="this.$t('button.Export the selected')" key="checked" value="checked"></el-option>
  </el-select>
</template>
<script>
import { downloadFile } from '@/api'
export default {
  props: {
    // 导出参数
    params: {
      required: true,
      type: Object
    },
    // 导出全部-接口地址
    url: {
      required: true,
      type: String
    },
    // 导出全部-表格当前列表(用于判断是否有数据有才能导出)
    list: {
      required: true,
      type: Array
    },
    // 导出选中-选中的列表
    select: {
      required: true,
      type: Array
    },
    // 导出选中-key标示 如传入waybillNo:waybillNos 则key取值为waybillNo导出时参数字段名为waybillNos
    keyStr: {
      type: String,
      default: 'id:ids'
    }
  },
  data() {
    return {
      value: this.$t('button.Export')
    }
  },
  methods: {
    /**
     * 导出
     * @param {String} type 导出类型
     */
    exportData(type) {
      this.value = this.$t('button.Export')
      // 验证
      if ((type === 'all' && this.list.length < 1) || (type === 'checked' && this.select.length < 1)) {
        this.$message({ showClose: false, center: true, message: this.$t('message.There is no data to export'), type: 'error' })
        return false
      }
      // 导出
      let param = {}
      if (type === 'checked') {
        let key1 = null
        let key2 = null
        if (this.keyStr) {
          const keys = this.keyStr.split(':')
          key1 = keys[0]
          key2 = keys[1]
        } else {
          key1 = 'id'
          key2 = 'ids'
        }
        param[key2] = []
        this.select.forEach((item) => {
          param[key2].push(item[key1])
        })
      } else if (type === 'all') {
        param = this.exportParams
      }
      downloadFile(this.exportUrl, param)
    }
  }
}
</script>
<style lang="less" scoped>
.export-btn{
  width: 100px;
  margin: 20px 20px 0;
}
</style>
